﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MongoDBManager
{
    public class MongoUtil
    {
        /// <summary>
        /// mongo客户端对象
        /// </summary>
        private MongoClient _client;

        /// <summary>
        /// mongo连接字符串对象
        /// </summary>
        private MongoUrl _mongoUrl;

        public bool IsSuccess { get; set; }

        /// <summary>
        /// 测试数据库是否连接成功
        /// </summary>
        public bool TestConnection(string monggodburl)
        {
            try
            {
                _mongoUrl = new MongoUrl(monggodburl);
                MongoClientSettings settings = MongoClientSettings.FromUrl(_mongoUrl); // 从url 中获取setting
                settings.ServerSelectionTimeout = new TimeSpan(0, 0, 5); // 设置寻找服务器的时间为5秒
                _client = new MongoClient(settings);
                _client.GetDatabase(_mongoUrl.DatabaseName);
                // 获取所有的数据库名
                _client.ListDatabaseNames();
                IsSuccess = true;
                Log.Info("mongodb connected Successful!");
            }
            catch (Exception)
            {
                IsSuccess = false;
                Log.Error("mongodb connected Failed!");
            }
            return IsSuccess;
        }

        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <returns></returns>
        private IMongoDatabase getMongoDatabase()
        {
            return _client.GetDatabase(_mongoUrl.DatabaseName);
        }

        public string GetDatabaseName()
        {
            return _mongoUrl.DatabaseName;
        }

        public List<string> GetListDatabaseNames()
        {
            return _client.ListDatabaseNames().ToList();
        }
        /// <summary>
        /// 获取所有文档的名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetDoucuments()
        {
            return getMongoDatabase().ListCollectionNames().ToList();
        }

        public void CreateCollection(string name)
        {
            _client.GetDatabase(_mongoUrl.DatabaseName).CreateCollection(name);
        }

        public List<BsonDocument> GetDoucument(string name)
        {
            return getMongoDatabase().GetCollection<BsonDocument>(name).Find(Builders<BsonDocument>.Filter.Empty).ToList();
        }

        public void InsertDoucument(string name, BsonDocument bjson)
        {
            getMongoDatabase().GetCollection<BsonDocument>(name).InsertOne(bjson);
        }
    }
}
